import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { CleanAttachment, GetCleanTask } from "@app";
import { EventsOff, EventsOn } from "@runtime";
import { Button, Progress, notification } from "antd";
import { cleanInfo as cleanInfoRedux, setCleanHandled, setCleanTotal } from '@/store/cleanInfo'
import { useEffect } from "react";

export function Clean() {
  const dispatch = useAppDispatch()
  const cleanInfo = useAppSelector(cleanInfoRedux)

  useEffect(() => {
    GetCleanTask().then(cleanInfo => {
      if (cleanInfo.running) {
        dispatch(setCleanTotal(cleanInfo.total))
        dispatch(setCleanHandled(cleanInfo.handled))
        eventHandler(cleanInfo.eventName)
      } else {
        dispatch(setCleanTotal(0))
        dispatch(setCleanHandled(0))
      }
    })
  }, [])

  const eventHandler = (eventName: string) => {
    EventsOn(eventName, (data) => {
      if (typeof data === 'boolean') {
        EventsOff(eventName)
        return
      }

      dispatch(setCleanHandled(data))
    })
  }

  const cleanAttachment = () => {
    dispatch(setCleanHandled(0))

    CleanAttachment().then(cleanInfo => {
      dispatch(setCleanTotal(cleanInfo.total))
      return cleanInfo.eventName
    }).then((eventName: string) => {
      eventHandler(eventName)
    }).catch(err => {
      notification.error({
        message: '清理错误',
        description: err,
      })
    })
  }

  return <>
    <div>
      <Button loading={cleanInfo.total != cleanInfo.handled} onClick={cleanAttachment}>清理</Button>
      {cleanInfo.handled} / {cleanInfo.total}
    </div>
    <Progress percent={cleanInfo.handled / cleanInfo.total * 100} showInfo={false} />
  </>
}
